const Address = require('@models/address');
const logger = require('@shared/utils/logger');
const { Op } = require('sequelize');

/**
 * 获取用户地址列表
 */
exports.getAddresses = async (req, res, next) => {
  try {
    const userId = req.user.id;
    logger.info(`[地址管理] 获取用户(${userId})的地址列表`);

    const addresses = await Address.findAll({
      where: { user_id: userId },
      order: [
        ['is_default', 'DESC'],  // 默认地址排在前面
        ['create_time', 'DESC']  // 新创建的地址排在前面
      ]
    });

    res.json({
      code: 200,
      message: 'success',
      data: addresses
    });
  } catch (error) {
    logger.error('[地址管理] 获取地址列表失败', error);
    next(error);
  }
};

/**
 * 获取默认地址
 */
exports.getDefaultAddress = async (req, res, next) => {
  try {
    const userId = req.user.id;
    logger.info(`[地址管理] 获取用户(${userId})的默认地址`);

    const address = await Address.findOne({
      where: {
        user_id: userId,
        is_default: 1
      }
    });

    res.json({
      code: 200,
      message: 'success',
      data: address || null
    });
  } catch (error) {
    logger.error('[地址管理] 获取默认地址失败', error);
    next(error);
  }
};

/**
 * 创建收货地址
 */
exports.createAddress = async (req, res, next) => {
  try {
    const userId = req.user.id;
    const { receiver, phone, province, city, district, detail, isDefault } = req.body;

    // 参数验证
    if (!receiver) {
      return res.status(400).json({
        code: 400,
        message: '收货人不能为空'
      });
    }
    if (!phone) {
      return res.status(400).json({
        code: 400,
        message: '手机号不能为空'
      });
    }
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      return res.status(400).json({
        code: 400,
        message: '手机号格式不正确'
      });
    }
    if (!province || !city || !district) {
      return res.status(400).json({
        code: 400,
        message: '地区信息不完整'
      });
    }
    if (!detail) {
      return res.status(400).json({
        code: 400,
        message: '详细地址不能为空'
      });
    }

    logger.info(`[地址管理] 用户(${userId})创建新地址`);

    // 如果设置为默认地址，需要取消其他默认地址
    if (isDefault) {
      await Address.update(
        { is_default: 0 },
        { where: { user_id: userId, is_default: 1 } }
      );
    }

    const address = await Address.create({
      user_id: userId,
      receiver,
      phone,
      province,
      city,
      district,
      detail,
      is_default: isDefault ? 1 : 0
    });

    res.json({
      code: 200,
      message: '添加成功',
      data: address
    });
  } catch (error) {
    logger.error('[地址管理] 创建地址失败', error);
    next(error);
  }
};

/**
 * 更新收货地址
 */
exports.updateAddress = async (req, res, next) => {
  try {
    const userId = req.user.id;
    const addressId = req.params.id;
    const { receiver, phone, province, city, district, detail, isDefault } = req.body;

    // 参数验证
    if (!receiver) {
      return res.status(400).json({
        code: 400,
        message: '收货人不能为空'
      });
    }
    if (!phone) {
      return res.status(400).json({
        code: 400,
        message: '手机号不能为空'
      });
    }
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      return res.status(400).json({
        code: 400,
        message: '手机号格式不正确'
      });
    }
    if (!province || !city || !district) {
      return res.status(400).json({
        code: 400,
        message: '地区信息不完整'
      });
    }
    if (!detail) {
      return res.status(400).json({
        code: 400,
        message: '详细地址不能为空'
      });
    }

    // 检查地址是否存在且属于当前用户
    const address = await Address.findOne({
      where: { id: addressId, user_id: userId }
    });

    if (!address) {
      return res.status(404).json({
        code: 404,
        message: '地址不存在'
      });
    }

    logger.info(`[地址管理] 用户(${userId})更新地址(${addressId})`);

    // 如果设置为默认地址，需要取消其他默认地址
    if (isDefault) {
      await Address.update(
        { is_default: 0 },
        { where: { user_id: userId, is_default: 1, id: { [Op.ne]: addressId } } }
      );
    }

    await address.update({
      receiver,
      phone,
      province,
      city,
      district,
      detail,
      is_default: isDefault ? 1 : 0
    });

    res.json({
      code: 200,
      message: '更新成功',
      data: address
    });
  } catch (error) {
    logger.error('[地址管理] 更新地址失败', error);
    next(error);
  }
};

/**
 * 删除收货地址
 */
exports.deleteAddress = async (req, res, next) => {
  try {
    const userId = req.user.id;
    const addressId = req.params.id;

    // 检查地址是否存在且属于当前用户
    const address = await Address.findOne({
      where: { id: addressId, user_id: userId }
    });

    if (!address) {
      return res.status(404).json({
        code: 404,
        message: '地址不存在'
      });
    }

    logger.info(`[地址管理] 用户(${userId})删除地址(${addressId})`);

    await address.destroy();

    res.json({
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    logger.error('[地址管理] 删除地址失败', error);
    next(error);
  }
};

/**
 * 设置默认地址
 */
exports.setDefaultAddress = async (req, res, next) => {
  try {
    const userId = req.user.id;
    const addressId = req.params.id;

    // 检查地址是否存在且属于当前用户
    const address = await Address.findOne({
      where: { id: addressId, user_id: userId }
    });

    if (!address) {
      return res.status(404).json({
        code: 404,
        message: '地址不存在'
      });
    }

    logger.info(`[地址管理] 用户(${userId})设置默认地址(${addressId})`);

    // 取消其他默认地址
    await Address.update(
      { is_default: 0 },
      { where: { user_id: userId, is_default: 1 } }
    );

    // 设置当前地址为默认地址
    await address.update({ is_default: 1 });

    res.json({
      code: 200,
      message: '设置成功',
      data: address
    });
  } catch (error) {
    logger.error('[地址管理] 设置默认地址失败', error);
    next(error);
  }
}; 